<template>
	<section>
		<!--工具条-->
    <!--高级查询-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true" >
				<el-form-item>
					<el-input v-model="keyWord" placeholder="请输入关键字！！！"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" v-on:click="departmentQuery">查询</el-button>
				</el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleAdd"  v-perm="'department:save'">新增</el-button>
        </el-form-item>
			</el-form>
		</el-col>

		<!--列表-->
		<el-table :data="departments" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
			<el-table-column type="selection" width="55">
			</el-table-column>
			<el-table-column type="index" width="60">
			</el-table-column>
      <el-table-column prop="sn" label="编号" width="120" sortable>
      </el-table-column>
			<el-table-column prop="name" label="姓名" width="120" sortable>
			</el-table-column>
			<el-table-column prop="dirPath" label="路径" width="100"  sortable>
			</el-table-column>
      <el-table-column prop="state" label="状态" width="100" sortable>
        <template slot-scope="scope">
          <span style="color: green" v-if="scope.row.state==1">正常</span>
          <span style="color: red" v-else-if="scope.row.state==0">停用</span>
        </template>
      </el-table-column>
			<el-table-column prop="manager.username" label="部门经理" width="120" sortable>
			</el-table-column>
			<el-table-column prop="parent.name" label="上一级部门" min-width="180" sortable>
			</el-table-column>
			<el-table-column label="操作" width="150">
				<template scope="scope">
					<el-button size="small" @click="handleEdit(scope.$index, scope.row)"
                     v-perm="'department:save'">编辑</el-button>
					<el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)"
                     v-perm="'department:delete'">删除</el-button>
				</template>
			</el-table-column>
		</el-table>

		<!--工具条-->
		<el-col :span="24" class="toolbar">
			<el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
			<el-pagination layout="prev, pager, next" @current-change="handleCurrentChange"
                     :current-page="currentPage" :page-size="pageSize"
                     :total="totals" style="float:right;">
			</el-pagination>
		</el-col>

		<!--编辑界面-->
		<el-dialog :title="title"  :visible.sync="saveFormVisible" :close-on-click-modal="false">
			<el-form :model="saveForm" label-width="80px" :rules="saveFormRules" ref="saveForm">
				<el-form-item label="部门编号" prop="sn">
					<el-input v-model="saveForm.sn" auto-complete="off"></el-input>
				</el-form-item>
        <el-form-item label="部门名称" prop="name">
          <el-input v-model="saveForm.name" auto-complete="off"></el-input>
        </el-form-item>
				<el-form-item label="是否启用">
					<el-radio-group v-model="saveForm.state">
						<el-radio class="radio" :label="1">启用</el-radio>
						<el-radio class="radio" :label="0">禁用</el-radio>
					</el-radio-group>
				</el-form-item>
				<el-form-item label="部门经理">
          <el-select v-model="saveForm.manager_id" placeholder="请选择">
            <el-option v-for="item in managers"
                       :label="item.username"
                       :value="item.id">
              <span style="float: left">{{ item.username }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.phone }}</span>
            </el-option>
          </el-select>
				</el-form-item>
				<el-form-item label="上级部门">
          <el-cascader v-model="saveForm.parent"
                       :options="deptTree"
                       :props="{
            	checkStrictly: true,
                label: 'name', // 级联框显示那个属性的值
                value: 'id'    // 回显时需要,回传值的时候也需要
            }" clearable>
          </el-cascader>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="saveFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="saveSubmit" :loading="saveLoading">提交</el-button>
			</div>
		</el-dialog>

	</section>
</template>

<script>

	export default {
		data() {
			return {
			  // 分页数据
        departments: [],  //绑定到表格 - 显示列表数据
        totals: 0,     //总数量 - 计算分页栏
			  currentPage:1,   //当前页 - 分页栏默认当前页显示
        pageSize:5,      //每页显示的条数  - 计算分页栏
        listLoading: false,  //表格上的加载框

        //高级查询
          keyWord:'',

        // 批量删除
				sels: [],//列表选中列

        //部门经理
        managers:[],

        // 部门树
        deptTree: [],


				saveFormVisible: false,//编辑界面是否显示
				saveLoading: false,
        title: '',
        saveFormRules: {
					sn: [
						{ required: true, message: '请输入部门编号', trigger: 'blur' }
					],name: [
          { required: true, message: '请输入部门名称', trigger: 'blur' }
        ]
				},
				//编辑界面数据
				saveForm: {
					id: null,
          sn: '',
					name: '',
					state: 1,
					manager_id: null,
					parent_id: null
				}
			}
		},
		methods: {
      //获取用户列表
      getDepartments() {
        let para = {
          // 分页数据
          currentPage:this.currentPage,
          pageSize:this.pageSize,

          // 高级查询数据
          keyWord:this.keyWord

        };

        //页面一加载就显示加载框
        this.listLoading = true;
        //NProgress.start();
        this.$http.post("/department",para).then((res) => {
          //赋值总数量
          this.totals = res.data.totals;
          //当前页的数据
          this.departments = res.data.data;
          //关闭加载框
          this.listLoading = false;
          //NProgress.done();
        }).catch(res=>{
          this.$message.error('系统繁忙，请稍后再试');
        });
      },handleCurrentChange(val) {
        this.currentPage = val;
        this.getDepartments();
      },

      // 高级查询
      departmentQuery(){
        this.currentPage=1,
        this.getDepartments()
      },

      //删除
      handleDel: function (index, row) {
        this.$confirm('确认删除该记录吗?', '提示', {
          type: 'warning'
        }).then(() => {
          this.listLoading = true;
          //NProgress.start();
        let  id = row.id ;
         this.$http.delete("/department/"+ id) .then((res) => {

            if (res.data.success){
              this.$message.success('删除成功');
              var totalPage=Math.ceil(this.totals/this.pageSize);
              if(totalPage==this.currentPage &&this.currentPage>1&&(this.totals-1)%this.pageSize==0){
                this.currentPage=this.currentPage-1;
              }


              this.getDepartments();
            }else{
              this.$message.error('删除失败，请稍后在试[500]！！！');
            }
           this.listLoading = false;
          }).catch(res=>{
           this.$message.error('删除失败，请稍后在试[400,404]！！！');
         });
        }).catch(() => {
        });
      },

      // 批量删除
      selsChange: function (sels) {
        this.sels = sels;
      },
      //批量删除
      batchRemove: function () {
        var ids = this.sels.map(item => item.id);
        this.$confirm('确认删除选中记录吗？', '提示', {
          type: 'warning'
        }).then(() => {
          this.listLoading = true;
          this.$http.patch("/department",ids).then(res=>{
            if (res.data.success){
              this.$message.success('删除成功');
              this.getDepartments();
            }else{
              this.$message.error('删除失败，请稍后在试[500]！！！');
            }
            this.listLoading = false;
          }).catch(res=>{
            this.$message.error('删除失败，请稍后在试[404,400]！！！');
          });
        }).catch(() => {
        });
      },
      //显示新增界面
      handleAdd: function () {
        this.saveForm = {
          id: null,
          sn: '',
          name: '',
          state: 1,
          manager_id: null,
          parent_id: null
        };
        this.title="添加";
        this.getManagers();
        this.getDeptTree();

        //显示对话框
        this.saveFormVisible = true;
      },

      //显示编辑界面
      handleEdit: function (index, row) {

        this.saveForm = Object.assign({}, row);
        this.title="修改";
        this.getManagers();
        this.getDeptTree();

        var dirPath = this.saveForm.dirPath;
        var arr = dirPath.split("/");
        var resultArr=[];
        for (var i=1;i<arr.length-1;i++){
          resultArr[i-1]=parseInt(arr[i]);
        }
        this.saveForm.parent = resultArr;
        this.saveFormVisible = true;
      },

      // 部门树
      getDeptTree(){
        this.$http.get("/department/deptTree").then(res => {
          this.deptTree = res.data;
        })
      },

      //编辑
      saveSubmit: function () {
        //所有对话框中  一个名称为 saveForm的对话框  验证【上面的验证规则通过了 - 返回true，否则返回false】
        this.$refs.saveForm.validate((valid) => {
          if (valid) {
            this.$confirm('确认提交吗？', '提示', {}).then(() => {
              this.saveLoading = true;
              let para = Object.assign({}, this.saveForm);

              var parentTmp =  para.parent;
              if (parentTmp){
                para.parent=null;
                para.parent_id = parentTmp[parentTmp.length-1];
              }


              this.$http.put("/department",para).then(res => {
                if(res.data.success){
                  this.$message.success("操作成功");
                  this.getDepartments();
                }else{
                  this.$message.error("系统繁忙，请稍后重试【500】")
                }
                this.saveLoading = false;
                this.saveFormVisible = false;
              }).catch(res => {
                this.$message.error("系统繁忙，请稍后重试【400,404】")
              })
            });
          }
        });
      },
      // 部门经理
      getManagers(){
        this.$http.get("/emp").then(res => {
          //给部门经理们赋值
          this.managers = res.data;
        })
      }
    },


		mounted() {
			this.getDepartments();
		}
	}

</script>

<style scoped>

</style>